import React from 'react';
import Canvas from "../../core/Canvas";
import QuoteLayer from '../../layer/QuoteLayer';
import OChart from '../../core/OChart';
import Event from '../../event/Event';

function rateToBar(isNew, data, price) {
  if (isNew) {
    data[data.length - 1].close = parseFloat(price);
    if (data[data.length - 1].high < parseFloat(price)) {
      data[data.length - 1].high = parseFloat(price);
    }
    if (data[data.length - 1].low > parseFloat(price)) {
      data[data.length - 1].low = parseFloat(price);
    }
    data[data.length - 1].datetime = new Date().getTime();
  } else {
    data.push({
      close: parseFloat(price),
      high: parseFloat(price),
      low: parseFloat(price),
      open: parseFloat(price),
      datetime: new Date().getTime()
    });
  }
}

export default class extends React.Component {
  constructor(props) {
    super(props);
    this.quoteRef = React.createRef();
  }

  /**
   * 动态更新数据
   * **/
  updateRate(price, ktype) {
    const { data } = this.quoteLayer;
    if (data.length === 0) {
      data.push({
        close: parseFloat(price),
        high: parseFloat(price),
        low: parseFloat(price),
        open: parseFloat(price),
        datetime: new Date().getTime()
      });
    } else if (data.length === 1) {

    } else {
      const lastTime = parseInt(data[data.length - 2].datetime);
      const currentTime = new Date().getTime();
      if (ktype === 0) {
        // 1分钟线
        rateToBar(lastTime + 60 * 1000 > currentTime, data, price);
      } else if (ktype === 1) {
        // 5分钟线
        rateToBar(lastTime + 5 * 60 * 1000 > currentTime, data, price);
      } else if (ktype === 2) {
        // 15分钟
        rateToBar(lastTime + 15 * 60 * 1000 > currentTime, data, price);
      } else if (ktype === 3) {
        // 30分钟线
        rateToBar(lastTime + 30 * 60 * 1000 > currentTime, data, price);
      } else if (ktype === 4) {
        // 小时线
        rateToBar(lastTime + 60 * 60 * 1000 > currentTime, data, price);
      } else if (ktype === 5) {
        // 4小时线
        rateToBar(lastTime + 4 * 60 * 60 * 1000 > currentTime, data, price);
      } else if (ktype === 6) {
        // 日线
        rateToBar(lastTime + 24 * 60 * 60 * 1000 > currentTime, data, price);
      } else if (ktype === 7) {
        rateToBar(lastTime + 7 * 24 * 60 * 60 * 1000 > currentTime, data, price);
      } else if (ktype === 8) {
        rateToBar(lastTime + 30 * 24 * 60 * 60 * 1000 > currentTime, data, price);
      }
    }
    this.quoteLayer.data = data;
    this.quoteLayer.make();
    this.canvas.paint();
  }

  componentWillReceiveProps(nextProps, nextContext) {
    const { data = [], name = '', chartName } = nextProps;
    if (data !== this.props.data) {
      this.quoteLayer.data = data;
      this.quoteLayer.make();
      this.canvas.paint();
    }
    if (name !== this.props.name) {
      OChart.remove(`${this.props.name}:onChartMaked`, this._onChartMaked);
      OChart.remove(`${this.props.name}:${chartName}:setQuote`, this._setQuote);
      OChart.remove(`${this.props.name}:${chartName}:setQuoteColor`, this._setQuoteColor);
      OChart.remove(`${this.props.name}:${chartName}:setQuoteParams`, this._setQuoteParams);
      OChart.remove(`${this.props.name}:updateRate`, this._updateRate);
      OChart.remove(`${this.props.name}:${chartName}:setQuoteStyle`, this._setQuoteStyle);
      OChart.remove(`${this.props.name}:${chartName}:getQuote`, this._getQuote);
      OChart.remove(`${this.props.name}:resize`, this._resize);
      OChart.on(`${name}:onChartMaked`, this._onChartMaked);
      OChart.on(`${name}:${chartName}:setQuote`, this._setQuote);
      OChart.on(`${name}:${chartName}:setQuoteColor`, this._setQuoteColor);
      OChart.on(`${name}:${chartName}:setQuoteParams`, this._setQuoteParams);
      OChart.on(`${name}:updateRate`, this._updateRate);
      OChart.on(`${name}:${chartName}:setQuoteStyle`, this._setQuoteStyle);
      OChart.on(`${name}:${chartName}:getQuote`, this._getQuote);
      OChart.on(`${name}:resize`, this._resize);
    }
  }

  _onChartMaked = (options) => {
    const { start, end, xStep, yStep } = options;
    this.quoteLayer.dataStart = start;
    this.quoteLayer.dataEnd = end;
    this.quoteLayer.xStep = xStep;
    this.quoteLayer.make();
    this.canvas.paint();
  }

  _setQuote = (options) => {
    this.quoteLayer.name = options.name;
    this.quoteLayer.make();
    this.canvas.paint();
  }

  _setQuoteColor = (options) => {
    this.quoteLayer.color = options.color;
    this.quoteLayer.make();
    this.canvas.paint();
  }

  _setQuoteParams = (options) => {
    this.quoteLayer.params = options;
    this.quoteLayer.make();
    this.canvas.paint();
  }

  _updateRate = (options) => {
    // 更新数据
    this.updateRate(options.price, options.ktype);
  }

  _setQuoteStyle = (styles) => {
    //设置指标的颜色
    let isChange = false;
    for(let key in styles) {
      if (key.indexOf('Color') >= 0) {
        //简单的校验，剔除不必要的修改问题，后续可以优化
        this.quoteLayer[key] = styles[key];
        isChange = true;
      }
    }
    if (isChange) {
      this.quoteLayer.make();
      this.canvas.paint();
    }
  }

  _getQuote = (options) => {
    const { shift = 0, resolve } = options;
    let quote = this.quoteLayer.getLegend(shift);
    resolve && resolve(quote);
  }

  _resize = () => {
      console.log('resize', this.quoteRef);
      if (
          this.quoteRef
          && this.quoteRef.current !== undefined
          && this.quoteRef.current !== null
      ) {
          this.save();
          this.quoteRef.current.innerHTML = '';
          setTimeout(() => {
              this.init();
              this.restore();
          }, 0);
      }
  }

  componentDidMount() {
    const { name = '', chartName = '' } = this.props;

    this.init();
    window.addEventListener('resize', (e) => {
        if (
            this.chartRef.current !== undefined
            && this.chartRef.current !== null
        ) {
            this.save();
            this.chartRef.current.innerHTML = '';
            setTimeout(() => {
                this.init();
                this.restore();
            }, 0);

        }
    });
    OChart.on(`${name}:onChartMaked`, this._onChartMaked);
    OChart.on(`${name}:${chartName}:setQuote`, this._setQuote);
    OChart.on(`${name}:${chartName}:setQuoteColor`, this._setQuoteColor);
    OChart.on(`${name}:${chartName}:setQuoteParams`, this._setQuoteParams);
    OChart.on(`${name}:updateRate`, this._updateRate);
    OChart.on(`${name}:${chartName}:setQuoteStyle`, this._setQuoteStyle);
    OChart.on(`${name}:${chartName}:getQuote`, this._getQuote);
    OChart.on(`${name}:resize`, this._resize);
  }

  save() {
      this.store = {
          name: this.quoteLayer.name,
          color: this.quoteLayer.color,
          params: this.quoteLayer.params
      };
  }

  restore() {
      Object.assign(this.quoteLayer, this.store);
  }

  componentWillUnmount() {
    const { name = '', chartName = '' } = this.props;
    OChart.remove(`${name}:onChartMaked`, this._onChartMaked);
    OChart.remove(`${name}:${chartName}:setQuote`, this._setQuote);
    OChart.remove(`${name}:${chartName}:setQuoteColor`, this._setQuoteColor);
    OChart.remove(`${name}:${chartName}:setQuoteParams`, this._setQuoteParams);
    OChart.remove(`${name}:updateRate`, this._updateRate);
    OChart.remove(`${name}:${chartName}:setQuoteStyle`, this._setQuoteStyle);
    OChart.remove(`${name}:${chartName}:getQuote`, this._getQuote);
    OChart.remove(`${name}:resize`, this._resize)
  }

  init() {
    const { data = [], name = '', chartName = '' } = this.props;
    this.canvas = new Canvas({
      ele: this.quoteRef.current,
      canAction: false
    });
    this.quoteLayer = new QuoteLayer(this.canvas, {
      width: this.canvas.width,
      height: this.canvas.height,
      data,
    });
    this.canvas.addChild(this.quoteLayer);
    this.quoteLayer.addEventListener(Event.EVENT_DRAG, (e) => {
      OChart.emit(`${name}:onQuoteDrag`, e);
    });
    this.quoteLayer.addEventListener(Event.EVENT_DRAG_END, (e) => {
      OChart.emit(`${name}:onQuoteDragEnd`, e);
    });
    this.quoteLayer.addEventListener(Event.EVENT_MOUSE_WHEEL, (e) => {
      OChart.emit(`${name}:onQuoteScale`, e);
    });

  }

  render() {
    const { className = '' } = this.props;
    return (
      <div className={className} ref={this.quoteRef} />
    );
  }
}
